import request from '@/utils/request'
import store from '@/store'

// 获取公告列表
export function apiGetAnnouncementList(params) {
  // 确保userId参数是有效的
  const userParams = { ...params }
  
  // 如果传入了userId参数且为负数或无效值，则从store中获取正确的userId
  if (userParams.userId && (userParams.userId < 0 || isNaN(userParams.userId))) {
    const userInfo = store.state.user.userInfo
    if (userInfo && userInfo.id) {
      userParams.userId = userInfo.id
    } else {
      // 如果无法获取有效的userId，则删除这个参数
      delete userParams.userId
    }
  }
  
  return request({
    url: '/announcement',
    method: 'get',
    params: userParams
  })
}

// 获取公告详情
export function getAnnouncementDetail(id, params) {
  return request({
    url: `/announcement/${id}`,
    method: 'get',
    params
  })
}

// 发布公告
export function apiPublishAnnouncement(data) {
  return request({
    url: '/announcement',
    method: 'post',
    data
  })
}

// 删除公告
export function apiDeleteAnnouncement(id, params) {
  return request({
    url: `/announcement/${id}`,
    method: 'delete',
    params
  })
}

// 草稿相关API
export function apiSaveDraft(data) {
  return request({
    url: '/announcement/draft',
    method: 'post',
    data
  })
}

export function apiUpdateDraft(data) {
  return request({
    url: '/announcement/draft',
    method: 'put',
    data
  })
}

export function apiGetDraftList(params) {
  return request({
    url: '/announcement/draft',
    method: 'get',
    params
  })
}

export function apiPublishDraft(id, params) {
  return request({
    url: `/announcement/draft/${id}/publish`,
    method: 'post',
    params
  })
}

export function apiDeleteDraft(id, params) {
  return request({
    url: `/announcement/draft/${id}`,
    method: 'delete',
    params
  })
}

// 获取我的发布
export function getMyAnnouncements(params) {
  return request({
    url: '/announcement/my',
    method: 'get',
    params
  })
}

// 附件上传API
export function uploadAttachment(file) {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/announcement/attachment/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 图片上传API
export function uploadImage(file) {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/announcement/image/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取公告附件列表
export function getAnnouncementAttachments(id) {
  return request({
    url: `/announcement/${id}/attachments`,
    method: 'get'
  })
} 